package com.crm.common.handler;

import com.crm.common.utils.JwtUtil;
import com.crm.common.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		log.info("......进入拦截器......");

		// 获取token
		String token = request.getHeader("Authorization");
		// 验证token
		try {
			// 如果是Bearer token格式，去掉前缀
			if (token != null && token.startsWith("Bearer ")) {
				token = token.substring(7);
			}
			Map<String, Object> claims = JwtUtil.parseToken(token);
			log.info("......解析的token为.....:{}", claims);
			ThreadLocalUtil.set(claims);
			// 放行拦截
			return true;
		} catch (Exception e) {
//			// 登录信息异常或未登录，http响应状态码为401
//			response.setStatus(401);
			// 拦截请求
			return true;
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// 清除ThreadLocal业务数据
		ThreadLocalUtil.remove();
	}
}

